package activity

import (
	"context"
	"github.com/gogf/gf/v2/os/gctx"
	"time"
	"xr-game-server/core/event"
	"xr-game-server/core/xrtimer"
	"xr-game-server/dao/activitydao"
	"xr-game-server/entity"
	"xr-game-server/gamecfg"
	"xr-game-server/gameevent"
	"xr-game-server/module/notice"
)

func onInit(msg any) {
	cfgs := gamecfg.GetAllActivityCfg()
	for _, cfg := range cfgs {
		//活动没有发布,跳过去
		if !cfg.Pub {
			continue
		}
		if cfg.Type != Common {
			continue
		}
		//检查活动是否开始
		now := time.Now()
		db := activitydao.GetActivityById(cfg.Id)
		if db == nil {
			db = entity.NewActivity(cfg.Id)
		}
		if now.After(cfg.GetStartTime()) {
			//查看活动是否已经广播过
			if !db.StartFlag {
				db.StartFlag = true
				activitydao.Save(db)
				//跑马灯
				event.Pub(gameevent.NoticeEvent, gameevent.NewCfgNoticeEventData([]any{cfg.Name}, notice.ActivityType))
				//活动通知
				event.Pub(gameevent.ActivityStartEvent, gameevent.NewActivityStartEventData(cfg.Id))
			}
		} else {
			//开始倒计时
			countDown := cfg.GetStartTime().Sub(now)
			xrtimer.AddOnce(gctx.New(), countDown, func(ctx context.Context) {
				dbNew := activitydao.GetActivityById(cfg.Id)
				if dbNew == nil {
					dbNew = entity.NewActivity(cfg.Id)
				}
				dbNew.StartFlag = true
				activitydao.Save(dbNew)
				//跑马灯
				event.Pub(gameevent.NoticeEvent, gameevent.NewCfgNoticeEventData([]any{cfg.Name}, notice.ActivityType))
				//活动通知
				event.Pub(gameevent.ActivityStartEvent, gameevent.NewActivityStartEventData(cfg.Id))
			})
		}
		//检查活动是否结束
		if now.After(cfg.GetEndTime()) {
			if !db.EndFlag {
				db.EndFlag = true
				activitydao.Save(db)
				//活动结束通知
				event.Pub(gameevent.ActivityEndEvent, gameevent.NewActivityEndEventData(cfg.Id))
				event.Pub(gameevent.NoticeEvent, gameevent.NewCfgNoticeEventData([]any{cfg.Name}, notice.ActivityType))
			}
		} else {
			countDown := cfg.GetEndTime().Sub(now)
			xrtimer.AddOnce(gctx.New(), countDown, func(ctx context.Context) {
				dbNew := activitydao.GetActivityById(cfg.Id)
				if dbNew == nil {
					dbNew = entity.NewActivity(cfg.Id)
				}
				dbNew.EndFlag = true
				activitydao.Save(dbNew)
				//活动结束通知
				event.Pub(gameevent.ActivityEndEvent, gameevent.NewActivityEndEventData(cfg.Id))
				event.Pub(gameevent.NoticeEvent, gameevent.NewCfgNoticeEventData([]any{cfg.Name}, notice.ActivityType))
			})
		}
	}
}
